<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px" size="mini">
      <el-row :gutter="15">
        <div class="orderNo">盘点单号：{{ form.wareCheckOdd }}</div>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="盘点主题" prop="wareCheckTitle">
            <el-input v-model="form.wareCheckTitle" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="盘点仓库" prop="wareId">
            <treeselect v-model="form.wareId" :normalizer="normalizer" :options="wareOptions" placeholder="请选择"
                        @select="handleTreeSelectNode"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="盘点人" prop="wareCheckPerson">
            <el-select v-model="form.wareCheckPerson" filterable placeholder="请选择">
              <el-option v-for="item in personOptions" :key="item.userId" :label="item.nickName"
                         :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="盘点方式" prop="wareCheckType">
            <el-select v-model="form.wareCheckType" clearable placeholder="请选择">
              <el-option key="0" :value="0" label="日常盘点"/>
              <el-option key="1" :value="1" label="定期盘点"/>
              <el-option key="2" :value="2" label="临时盘点"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="盘点日期" prop="wareCheckTime">
            <el-date-picker v-model="form.wareCheckTime" clearable placeholder="请选择" type="datetime"
            format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button :disabled="!form.wareId" icon="el-icon-plus" plain size="mini" type="primary"
                     @click="handleAddCommodity">添加商品
          </el-button>
          <el-button :disabled="!form.wareId && form.detailsList.length == 0" icon="el-icon-download" plain size="mini" type="primary"
                     @click="handleExportExcel">导出商品
          </el-button>
          <el-button :disabled="!form.wareId" icon="el-icon-upload2" plain size="mini" type="primary"
                     @click="handleImportExcel">导入商品
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-table v-loading="loading" :data="form.detailsList" id="educe-table" border>
          <el-table-column align="center"  label="商品ID" prop="commodityId"/>
          <el-table-column align="center" label="商品编号" prop="commodityNo"/>
          <el-table-column align="center" label="商品名称" prop="commodityName1"/>
          <el-table-column align="center" label="商品图片" prop="commodityImg" width="100"  class-name="noExport">
            <template slot-scope="scope">
              <image-preview :height="50" :src="scope.row.commodityImg" :width="50"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品类别" prop="commodityType"/>
          <el-table-column align="center" label="商品单价" prop="costPrice"/>
          <el-table-column align="center" label="规格" prop="commoditySpec" width="80"/>
          <el-table-column align="center" label="单位" prop="unitName1" width="150"/>
          <el-table-column align="center" label="当前库存" prop="wareCommodityNumber"/>
          <el-table-column align="center" label="实盘数量" prop="wareCheckNumber" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.wareCheckNumber" @input="calculate(scope.row)"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="盈亏数量" prop="quantityNumber"  class-name="noExport"/>
          <el-table-column align="center" label="盈亏金额" prop="quantityPrice"  class-name="noExport">
            <template slot-scope="scope">
              {{ toMoney(scope.row.quantityPrice) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="盘点结果" prop="quantityResult"  class-name="noExport">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.quantityResult == 0" type="warning">盘盈</el-tag>
              <el-tag v-if="scope.row.quantityResult == 1" type="danger">盘亏</el-tag>
              <el-tag v-if="scope.row.quantityResult == 2" type="success">正常</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" class-name="small-padding fixed-width noExport" label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" size="mini" type="text"
                         @click="handleDeleteCommodity(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :autosize="{ minRows: 4, maxRows: 4 }" placeholder="请输入"
                      type="textarea"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer-options">
      <el-button type="primary" @click="submitForm(0)">保存草稿</el-button>
      <el-button type="primary" @click="submitForm(1)">提交审核</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCommodityOpen" append-to-body title="选择商品"
               width="80%">
      <ErpCommodity v-if="isCommodityOpen" :notCommodityIds="notCommodityIds" :wareId="form.wareId"
                    @SelectionChange="handleSelectionChange">
      </ErpCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>


     <!-- 导入商品 -->
     <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload ref="upload" :action="upload.url + '?updateSupport=' + upload.updateSupport" :auto-upload="false" :disabled="upload.isUploading"
                 :headers="upload.headers" :limit="1"
                 :on-success="handleFileSuccess" accept=".xlsx, .xls" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {addErpWareCheck, getErpWareCheck, updateErpWareCheck} from "@/api/erp/ErpWareCheck";
import {getListErpCommodity} from '@/api/erp/ErpCommodity'
import {getSysUserList} from '@/api/system/user'
import {listErpWareHouse} from "@/api/erp/ErpWareHouse";
import ErpCommodity from '@/views/erp/ErpCommodity/selectedCommodity'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";
import FileSaver from 'file-saver'
//在引用过程中可能会出现版本的冲突
import * as XLSX from 'xlsx'
//将引用方式改为这个就行了

export default {
  components: {
    ErpCommodity,
    Treeselect
  },
  props: [],
  data() {
    return {
      // 盘点仓库
      wareOptions: [],
      // 盘点人
      personOptions: [],
      // 选择商品页面
      isCommodityOpen: false,
      form: { },
      rules: {
        wareCheckTitle: [
          {required: true, message: "盘点主题不能为空", trigger: "blur"}
        ],
        wareId: [
          {required: true, message: "盘点仓库不能为空", trigger: "blur"}
        ],
        wareCheckPerson: [
          {required: true, message: "盘点人不能为空", trigger: "blur"}
        ],
        wareCheckType: [
          {required: true, message: "盘点方式不能为空", trigger: "blur"}
        ],
        wareCheckTime: [
          {required: true, message: "盘点日期不能为空", trigger: "blur"}
        ],
      },
      // 商品导入参数
      upload: {
        // 是否显示弹出层（商品导入）
        open: false,
        // 弹出层标题（商品导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/erp/ErpWareCheck/importCommodityData"
      },
    }
  },
  created() {
    this.reset();
    this.handleGetListSysUser();
    this.getTreeselect();
    const wareCheckId = this.$route.params && this.$route.params.wareCheckId;
    if (wareCheckId != 0) {
      this.getWareCheckInfo(wareCheckId);
    } else {
      this.loading = false;
    }
  },
  mounted() {

  },
  methods: {
    // 获取详情
    getWareCheckInfo(id) {
      getErpWareCheck(id).then(response => {
        this.form = response.data;
      });
    },
    // 获取用户列表
    handleGetListSysUser() {
      getSysUserList().then(res => {
        this.personOptions = res.data;
      })
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect() {
      listErpWareHouse().then(response => {
        this.wareOptions = this.handleTree(response.data, "wareId", "warePid");
      });
    },
    // 仓库选择
    handleTreeSelectNode(e) {
      const loading = this.$loading({
          lock: true,
          text: '正在加载库存商品列表...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      // 查询该仓库下所有商品信息
      this.form.detailsList = [];
      getListErpCommodity({
        params: {
          wareId: e.wareId
        }
      }).then(res => {
         res.data.forEach( item => {
          item.wareCheckNumber =  item.wareCommodityNumber;
          item.quantityResult = 2;
          item.quantityNumber = 0;
          item.quantityPrice = 0;
        })
        this.form.detailsList = res.data;
        loading.close();
      })
    },
    // 选择商品
    handleAddCommodity() {
      // 设置商品过滤id
      this.notCommodityIds = this.form.detailsList?.map(item => item.commodityId);
      this.isCommodityOpen = true;
    },
    /** 提交按钮 */
    submitForm(approveStatus) {
      if(this.form.detailsList.length == 0){
        return this.$message.error('请选择盘点商品！');;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.approveStatus = approveStatus;
          if (this.form.wareCheckId != null) {
            updateErpWareCheck(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              const obj = {path: "/psi/stock/ErpWareCheck", name: "ErpWareCheck"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          } else {
            addErpWareCheck(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              const obj = {path: "/psi/stock/ErpWareCheck", name: "ErpWareCheck"};
              this.$tab.closeOpenPage(obj);
              this.$tab.refreshPage(obj);
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      const obj = {path: "/psi/stock/ErpWareCheck", name: "ErpWareCheck"};
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.temporyList.forEach((item) => {
        this.form.detailsList.push({
          ...item,
          wareCheckNumber: item.wareCommodityNumber,
          quantityResult: 2,
          quantityNumber: 0,
          quantityPrice: 0
        });
      });
      this.isCommodityOpen = false;
    },
    /** 删除商品 */
    handleDeleteCommodity(row) {
      const index = this.form.detailsList.indexOf(row);
      if (index > -1) {
        this.form.detailsList.splice(index, 1);
      }
    },
    // 表单重置
    reset() {
      this.form = {
        wareCheckOdd: 'PD' + this.parseTime(new Date(), '{y}{m}{d}{h}{i}{s}'),
        wareId: null,
        wareCheckTitle: null,
        wareCheckType: null,
        wareCheckTime: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
        remark: null,
        createId: null,
        createName: null,
        createTime: null,
        flag: null,
        approveStatus: null,
        approveId: null,
        approveName: null,
        approveTime: null,
        rejectTime: null,
        rejectReason: null,
        detailsList: []
      };
      this.resetForm("form");
    },
    // 计算
    calculate(item) {
      let quantityNumber = item.wareCommodityNumber - item.wareCheckNumber;
      item.quantityNumber = Math.abs(quantityNumber);
      item.quantityPrice = item.quantityNumber * item.costPrice;
      item.quantityResult = quantityNumber < 0 ? 0 : (quantityNumber > 0 ? 1 : 2);
    },
    // 导出表格
    handleExportExcel() {
      let tables = document.getElementById("educe-table").cloneNode(true)
      let header = tables.querySelector('table.el-table__header')
      let body = tables.querySelectorAll('table.el-table__body').length == 1 ? tables.querySelectorAll('table.el-table__body')[0] : tables.querySelectorAll('table.el-table__body')[tables.querySelectorAll('table.el-table__body').length - 1]
      let delCell = tables.querySelectorAll('.noExport')
      if (delCell && delCell.length){
        for (let i = 0;i < delCell.length;i++){
        delCell[i].remove()
        }
      }
      let wrapdiv = document.createElement('div')
      wrapdiv.appendChild(header)
      wrapdiv.appendChild(body)
      console.log('div:', wrapdiv)
      // 根据table生成Book工作簿
      let wb = XLSX.utils.table_to_book(wrapdiv)
      // 将Book工作簿作为输出
      let wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      // 尝试将当前table内容保存为excel文件
      try {
        FileSaver.saveAs(
          // 被导出的blob二进制对象
          new Blob([wbout], { type: 'application/octet-stream' }),
          // 导出文件的名称+后缀名
          '商品导出.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
    },
    // 导入表格
    handleImportExcel(){
      this.upload.title = "商品导入";
      this.upload.open = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleFileSuccess(response, file, fileList) {
      if(response.code == 200){
        response.data.forEach( item => {
          item.quantityNumber = item.wareCommodityNumber - item.wareCheckNumber;
          item.quantityPrice = item.quantityNumber * item.costPrice;
          if(item.quantityNumber == 0){
            item.quantityResult = 2
          }else if(item.quantityNumber > 0){
            item.quantityResult = 1;
          }else if(item.quantityNumber < 0){
            item.quantityResult = 0
          }
        })
        this.form.detailsList =  response.data
        this.upload.open = false;
      }
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
    },
  }
}

</script>
<style scoped>
.el-select {
  width: 100%;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
